package com.caimiao.miao.http.rxjava.observer;

import android.content.Context;

import com.caimiao.miao.widget.HttpBarDialog;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class CustomObserver<T> implements Observer<T>, HttpBarDialog.OnCancelListener {
    private CompositeDisposable mComposite;
    private HttpBarDialog mBarDialog;

    public CustomObserver(CompositeDisposable mComposite) {
        this(mComposite, null);
    }

    public CustomObserver(CompositeDisposable composite, Context context) {
        this.mComposite = composite;
        if (mComposite == null || mComposite.isDisposed())
            mComposite = new CompositeDisposable();
        if (context != null) {
            mBarDialog = new HttpBarDialog(context, this::dismissProgressDialog);
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (mComposite != null) mComposite.add(d);
        showProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
        e.printStackTrace();
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
    }

    @Override
    public void onCancelProgress() {
        mComposite.dispose();
    }

    private void showProgressDialog() {
        if (mBarDialog != null) mBarDialog.show();
    }

    private void dismissProgressDialog() {
        if (mBarDialog != null) {
            mBarDialog.dismiss();
            mBarDialog = null;
        }
    }
}
